package com.xuecheng.content.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.constants.MediaConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.WorkBindDto;
import com.xuecheng.commons.model.dto.WorkDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.domain.TeachplanWork;
import com.xuecheng.content.mapper.TeachplanWorkMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.content.service.TeachplanWorkService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.teaching.api.TeachingClient;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-08-14
 */
@Service
public class TeachplanWorkServiceImpl extends ServiceImpl<TeachplanWorkMapper, TeachplanWork> implements TeachplanWorkService {

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private TeachingClient teachingClient;

    @Autowired
    private TeachplanWorkService teachplanWorkService;

    @Autowired
    private CourseBaseService courseBaseService;

    // 作业绑定
    @Override
    public ResponseResult association(WorkBindDto dto) {
        // 1.校验参数合法性
        if (ObjectUtil.isEmpty(dto.getWorkId()) || ObjectUtil.isEmpty(dto.getTeachplanId())) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        // 2.判断课程状态
        // 2-1 先查课程计划
        Teachplan teachplan = teachplanService.getById(dto.getTeachplanId());
        // 2-2 再查课程信息
        CourseBase courseBase = courseBaseService.getById(teachplan.getCourseId());
        // 2-3 判断（已提交、已审核、已发布，不允许绑定）
        String auditStatus = courseBase.getAuditStatus();
        if (StrUtil.equals(auditStatus, CourseConstants.AUDIT_COMMIT_STATUS) ||
                StrUtil.equals(auditStatus, CourseConstants.AUDIT_PASTED_STATUS) ||
                StrUtil.equals(auditStatus, CourseConstants.AUDIT_PUBLISHED_STATUS)) {
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
        // 3.feign远程调用作业微服务
        ResponseResult<WorkVo> responseResult = teachingClient.findById(dto.getWorkId());
        // 3-1 判断状态码
        if (responseResult.getCode() != 0) {
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
        // 3-2 取出作业对象
        WorkVo workVo = responseResult.getData();
        // 4.封装作业绑定对象
        TeachplanWork teachplanWork = new TeachplanWork();
        teachplanWork.setWorkId(workVo.getWorkId()); // 作业id
        teachplanWork.setTeachplanId(teachplan.getId()); // 计划id
        teachplanWork.setCourseId(courseBase.getId()); // 课程id
        teachplanWork.setWorkFilename(workVo.getTitle()); // 作业名
        teachplanWork.setCreateDate(DateUtil.date());// 创建时间
        teachplanWork.setCreatePeople(AuthInfoHolder.getUserId().toString()); // 创建人
        teachplanWork.setChangePeople(AuthInfoHolder.getUserId().toString()); //修改人
        teachplanWork.setCompanyId(AuthInfoHolder.getCompanyId()); //机构id
        // 5.保存
        teachplanWorkService.save(teachplanWork);

        //  6.课程计划中的media_type作业
        teachplan.setMediaType(MediaConstants.WORK);
        teachplanService.updateById(teachplan);

        //  7.修改作业的绑定的课程
        WorkDto workDto = BeanHelper.copyProperties(workVo, WorkDto.class);
        workDto.setWorkId(workVo.getWorkId());
        workDto.setCourseName(courseBase.getName());
        ResponseResult response = teachingClient.saveOrUpdateWork(workDto);
        if (response.getCode() != 0) {//修改失败
            throw new BusinessException(ErrorCode.ERROR);
        }

        // 8.返回ok
        return ResponseResult.okResult();
    }

    //  作业解绑
    @Override
    public ResponseResult delete(Long teachplanWorkId, Long courseBaseId) {
        //  查课程信息
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        //  判断（已提交、已审核、已发布，不允许删除）
        String auditStatus = courseBase.getAuditStatus();
        if (StrUtil.equals(auditStatus, CourseConstants.AUDIT_COMMIT_STATUS) ||
                StrUtil.equals(auditStatus, CourseConstants.AUDIT_PASTED_STATUS) ||
                StrUtil.equals(auditStatus, CourseConstants.AUDIT_PUBLISHED_STATUS)) {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        //删除数据库
        LambdaQueryWrapper<TeachplanWork> qw = new LambdaQueryWrapper<>();
        qw.eq(TeachplanWork::getId, teachplanWorkId);
        boolean isSuccess = this.remove(qw);

        //修改 课程计划中的media_type应该设置为
        Teachplan teachplan = new Teachplan();
        teachplan.setMediaType(MediaConstants.WORK);
        teachplanService.updateById(teachplan);
        return ResponseResult.okResult(isSuccess);
    }

    //批阅详情-统计数据
    @Override
    public ResponseResult getInfo(Long courPubId) {
        //1. 根据课程发布id查询中间表
        LambdaQueryWrapper<TeachplanWork> qw = new LambdaQueryWrapper<>();
        qw.eq(ObjectUtil.isNotEmpty(courPubId),TeachplanWork::getCourseId,courPubId);
        List<TeachplanWork> list = this.list(qw);
        //判空
        if (CollectionUtil.isEmpty(list)) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        //2. 查询课程计划大纲
        ResponseResult responseResult = teachplanService.treeNodes(courPubId);
        //判空
        if (responseResult.getCode() != 0) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        //  课程计划信息
        TeachplanVo teachplanVo = (TeachplanVo) responseResult.getData();
        TeachWorkVo teachWorkVo = new TeachWorkVo();
        teachWorkVo.setPname(teachplanVo.getPname());
        teachWorkVo.setTeachPlanId(teachWorkVo.getTeachPlanId());
        List<TeachWorkVo> teachWorkVoList = new ArrayList<>();
        teachWorkVoList.add(teachWorkVo);

        //初始化集合
        List<WorkVo> workVoList = new ArrayList<>();
        //3。 根据列表查询到workId
        int courseIncludeWorkNums = list.size();//作业总数
        for (TeachplanWork teachplanWork : list) {
            //2-1 查询作业表
            ResponseResult<WorkVo> workResult = teachingClient.findById(teachplanWork.getWorkId());
            WorkVo workVo = workResult.getData();
            //补充数据
            workVoList.add(workVo);
        }

        //4. 根据coursePubId查询课程作业统计
        ResponseResult<CourseWorkRecVo> workRecResult = teachingClient.findMsgByCourseId(courPubId);
        CourseWorkRecVo workRecVo = workRecResult.getData();

        //5.转vo
        //5-1 作业统计
        WorkDateVo workDateVo = BeanHelper.copyProperties(workRecVo, WorkDateVo.class);
        //5-2 大纲
        workDateVo.setTeachPlan(teachWorkVoList);
        //5-3 作业信息
        workDateVo.setWorkList(workVoList);

        //  补充字段
        workDateVo.setCourseIncludeWorkNums(courseIncludeWorkNums); //课程包含的作业数
        workDateVo.setCommitterNumber(workRecVo.getAnswerNumber());    //  提交作业人数
        workDateVo.setContentName(workRecVo.getCourseName());   //  课程名称
        workDateVo.setLearnerNumber(1); //  todo 课程总人数

        //返回
        return ResponseResult.okResult(workDateVo);
    }
}
